include_shared('ajaxian');

function initializeProductListPage() {
	var prodContForms = $$$('form', $('products-container'));
	$$('input', prodContForms[0]).style.display = 'none';
	$$('input', prodContForms[2]).style.display = 'none';
	addEventHandler($$$('select',prodContForms[0])[1], 'change', perPageDropChange, false);
	addEventHandler($$$('select',prodContForms[2])[1], 'change', perPageDropChange, false);
	
}

function perPageDropChange(e) {
	setcookie('pref[perpage]', getEventTarget(e).value);
	makeAJAXRequest(window.location + '?&reqType=json', updateProductList, false, {responseType:'json'})
}

function updateProductList(json_response) {
	var products = eval('(' + json_response + ')');

	var productListingDiv = createDiv({id:'product-listing'});

	for (i = 0; i < products.length; i++) {
		var productDiv = createDiv({className:'product'});

		var compareBoxDiv = createDiv({className:'compare-box'});
		AC(compareBoxDiv, createInput({'type':'checkbox', 'value':products[i].id, 'name':'compare'}));
		AC(productDiv, compareBoxDiv);

		var priceDiv = createDiv({className:'price'});
		AC(priceDiv, document.createTextNode('$'+products[i]['price']));
		AC(priceDiv, createLink('Add to Cart', rootUrl+'addToCart/'+products[i].id));
		AC(productDiv, priceDiv);

		var imageDiv = createDiv({className:'image'});
		AC(imageDiv, document.createTextNode('no Image yet'));
		AC(productDiv, imageDiv);

		var prodDescDiv = createDiv({className:'product-description'});
		AC(prodDescDiv, createLink(products[i]['name'], rootUrl+'viewProduct/'+products[i].id));
		var prodDescUL = CE('ul');
		var tempLI = CE('li');
		tempLI.innerHTML = products[i].description;
		AC(prodDescUL, tempLI);
		tempLI = CE('li');
		tempLI.innerHTML = 'Material: ' + products[i].material;
		AC(prodDescUL, tempLI);
		tempLI = CE('li');
		tempLI.innerHTML = 'Dimension: ' + products[i].length + '\' x ' + products[i].width + '\' x ' + products[i].height + '\'(H)';
		AC(prodDescUL, tempLI);
		AC(prodDescDiv, prodDescUL);
		AC(productDiv, prodDescDiv);

		AC(productListingDiv, productDiv);
	}
	var origProdListing = $('product-listing');
	origProdListing.parentNode.replaceChild(productListingDiv, origProdListing);


}

addEventHandler(window, 'load', initializeProductListPage, false);